﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;

namespace CPXamarinPortable
{
    
    public class CPAuth
    {
        static string clientId = "WRymObjweyg9fj78Z5FV3R-uHeoVt_Oh";
        static string clientSecret = "NQyjvo7N7eN06Xu9nTHm4jRt0X7IZThNwPAKVnp9GBcOZKm89xIOhbeOIQrOXVJj";

        // The server base address
        static string baseUrl = "https://api.codeproject.com/";

        // this will hold the Access Token returned from the server.
        static string accessToken = "QDa8teqcpb9ry4TolEouG4HEZg4abdqN26FMU4C21wg5SOSiysb5tDhQx0M89xzv5T0mbLl0aXTAam8GFijwytrhr15ebU4LQRUwOvCXkatMm6w1WGwd1zrF52HAO4OuVud7EYhZL-X6Xq_tt7tT9zZYv03tKmO4lJORzTOQdCPVipiwlXEziLjEArZnCbIdA6VCsSNudb0ID4o1f5H0ZhYUaZCSCDksdgVHOcD5BqCrBMlfEx35YKT9nqVazE1EM3aMOTKyqjMnFDg4C4RSfDdWWzObACvwtG7sDkhwT_SVbcQGK14oVy_dmJJICL8SKXxUsWErFfWK-T_JzgSt1XNFyYV5J-Jnl6IViKrlk9hjRTljuq5EFbTtOLE5IDkPMP2bfv37eHVmXlAmwO1rjJAMwDQIQSJ-eTVNcp5uCWAWVLn8183icvx4X7J5ggYJIxIvgKAS8xxhk8xdPKuK3MkvKk56Qj6nRX4iUhc1Olmoz4pq";

        public static async void DoIt()
        {
            var accessToken = await MyArticles(1);
        }

        /// <summary>
        /// This method uses the OAuth Client Credentials Flow to get an Access Token to provide
        /// Authorization to the APIs.
        /// </summary>
        /// <returns></returns>
        private static async Task<string> GetAccessToken()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);

                // We want the response to be JSON.
               client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                // Build up the data to POST.
                List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
                postData.Add(new KeyValuePair<string, string>("client_id", clientId));
                postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                postData.Add(new KeyValuePair<string, string>("username", "asthanarht@gmail.com "));
                postData.Add(new KeyValuePair<string, string>("password", "#include"));
                FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
                // Post to the Server and parse the response.
                try
                {
                    var response = await client.PostAsync("Token", content);
                    response.EnsureSuccessStatusCode();
                    string jsonString = response.Content.ReadAsStringAsync().Result;
                    object responseData = JsonConvert.DeserializeObject(jsonString);
                    // return the Access Token.
                    return responseData.ToString();
                }
                catch (Exception ex)
                {
                    
                    throw;
                }
               
            }
        }

        public static async Task<List<KeyValuePair<string ,string>>> MyProfile()
        {
            using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Add the Authorization header with the AccessToken.
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                // create the URL string.
                string url = string.Format("v1/My/Profile");

                // make the request
                HttpResponseMessage response = await client.GetAsync(url);

                // parse the response and return the data.
                string jsonString = await response.Content.ReadAsStringAsync();
                var responseData = JsonHelper.Deserialize<MyProfileModel>(jsonString);
                var filterPairData = new List<KeyValuePair<string, string>>();

                filterPairData.Add(new KeyValuePair<string, string>("Name", responseData.UserName));
                filterPairData.Add(new KeyValuePair<string, string>("Member Id", Convert.ToString(responseData.CodeProjectMemberId)));
                filterPairData.Add(new KeyValuePair<string, string>("Country", responseData.Country));
                filterPairData.Add(new KeyValuePair<string, string>("Display Name", responseData.DisplayName));
                filterPairData.Add(new KeyValuePair<string, string>("Job Title", responseData.JobTitle));
                return filterPairData;
            }
        }

        /// <summary>
        /// Gets the user's Reputation.
        /// </summary>
        /// <returns>The user's Reputation.</returns>
        private static async Task<MyReputation> MyReputation()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Add the Authorization header with the AccessToken.
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                // create the URL string.
                string url = string.Format("v1/My/Reputation");

                // make the request
                HttpResponseMessage response = await client.GetAsync(url);

                // parse the response and return the data.
                var jsonString = await response.Content.ReadAsStringAsync();
                var responseData = JsonHelper.Deserialize<MyReputation>(jsonString);
                return responseData;
            }
        }

        /// <summary>
        /// Gets the page of Articles.
        /// </summary>
        /// <param name="page">The page to get.</param>
        /// <returns>The page of articles.</returns>
        private static async Task<MyArticles> MyArticles(int page)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Add the Authorization header with the AccessToken.
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                // create the URL string.
                string url = string.Format("v1/My/Articles?page={0}", page);

                // make the request
                HttpResponseMessage response = await client.GetAsync(url);

                // parse the response and return the data.
                string jsonString = await response.Content.ReadAsStringAsync();
                var responseData = JsonHelper.Deserialize<MyArticles>(jsonString);
                return responseData;
            }
        }


        /// <summary>
        /// Gets the page of Questions.
        /// </summary>
        /// <param name="page">The page to get.</param>
        /// <returns>The page of articles.</returns>
        private static async Task<MyQuestions> MyQuestions(int page)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Add the Authorization header with the AccessToken.
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                // create the URL string.
                string url = string.Format("v1/My/Questions?page={0}", page);

                // make the request
                HttpResponseMessage response = await client.GetAsync(url);

                // parse the response and return the data.
                string jsonString = await response.Content.ReadAsStringAsync();
                var responseData = JsonHelper.Deserialize<MyQuestions>(jsonString);

                return responseData;
            }
        }
    }
}
